<template>
  <div>
    <slot name="left" />
    <span :id="uuid" ref="count-up"></span>
    <slot name="right" />
  </div>
</template>

<script>
import uuid from 'uuid'
import CountUp from 'countup'
export default {
  name: 'CountUp',
  props: {
    startVal: {
      type: Number,
      default: 0
    },
    endVal: {
      type: Number,
      required: true
    },
    decimals: {
      type: Number,
      default: 0
    },
    duration: {
      type: Number,
      default: 1
    },
    useEasing: {
      type: Boolean,
      default: false
    },
    useGrouping: {
      type: Boolean,
      default: true
    },
    separator: {
      type: String,
      default: ','
    },
    decimal: {
      type: String,
      default: '.'
    },
    delay: {
      type: Number,
      default: 0
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.countUp = new CountUp(
        this.uuid,
        this.startVal,
        this.endVal,
        this.decimals,
        this.duration,
        {
          useEasing: this.useEasing,
          useGrouping: this.useGrouping,
          separator: this.separator,
          decimal: this.decimal
        }
      )
      setTimeout(() => {
        this.countUp.start()
        this.emitUpdateEvent()
      }, this.delay)
    })
  },
  computed: {
    uuid() {
      return uuid()
    }
  },
  methods: {
    getCount() {
      return this.endVal
    },
    emitUpdateEvent() {
      setTimeout(() => {
       this.$nextTick(() => {
          this.$emit('update-end',this.endVal)
       })
      }, this.duration * 1000 )
    }
  },
  watch: {
    endVal(newVal, oldVal) {
      if (newVal != undefined) {
        this.countUp.update(newVal)
        this.emitUpdateEvent()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.left, .right{
  font-size: 16px;
  font-weight: normal;
}
</style>
